/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.wx.handler;

import cn.ac.iie.di.wx.httpservice.HttpSender;
import cn.ac.iie.di.commons.httpserver.framework.handler.HandlerI;
import cn.ac.iie.di.commons.httpserver.framework.util.ParseRequestStream;
import cn.ac.iie.di.wx.common.RuntimeEnv;
import cn.ac.iie.di.wx.vo.ReadCntVo;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Request;

/**
 *
 * @author Administrator
 */
public class WxReadCnt implements HandlerI {

    static Logger logger = Logger.getLogger(WxReadCnt.class.getName());

    @Override
    public void execute(Request pRequest, HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {

            byte[] bytesContent = new byte[1024 * 2];
            int bytesReadIn = 0;
            ServletOutputStream out = response.getOutputStream();
            BufferedOutputStream bos = new BufferedOutputStream(out);
            //查库获取图片url，进行拼接后发送response,http连接资源释放问题需要注意
            String urlStr = ParseRequestStream.parseRequestStreamAsString(pRequest.getInputStream());
            urlStr=java.net.URLDecoder.decode(urlStr, "utf-8");
            logger.info(urlStr);
            String result = "";
            HttpSender hs = new HttpSender();
            if (RuntimeEnv.wxReadCntLimit.incrementAndGet() <= Integer.parseInt((String) RuntimeEnv.getParam(RuntimeEnv.WXREADCNTLIMIT))) {
                RuntimeEnv.wxReadCntCount.incrementAndGet();
                try {
                    String urlresult = hs.sendStringByUrl(urlStr, (String) RuntimeEnv.getParam(RuntimeEnv.wxReadCntUrl));//json的字符串
                    if (!urlresult.isEmpty()) {
                        logger.info(urlresult);
                        JSONObject jSONObject = JSONObject.parseObject(urlresult);
                        String data = jSONObject.getString("data");
                        if (!data.isEmpty()) {
                            JSONObject read_cntObject = JSONObject.parseObject(data);//获取的阅读数
                            String readcnt = read_cntObject.getString("read_cnt");
                            if (!readcnt.isEmpty()) {
                                result = urlresult;
                                JSONObject requestObject = JSONObject.parseObject(urlStr);
                                String url = requestObject.getString("url");
                                RuntimeEnv.readCntWxmsgGBlockingQueue.put(new ReadCntVo(url, readcnt));
                                RuntimeEnv.readCntWxmsgIBlockingQueue.put(new ReadCntVo(url, readcnt));
                                RuntimeEnv.readCntDocinfoBlockingQueue.put(new ReadCntVo(url, readcnt));
                            } else {
                                result = urlresult;
//                                    logger.info("read_cnt is empty");
                            }
                        } else {
                            result = urlresult;
                            String errorinfo = jSONObject.getString("errorinfo");
//                                logger.info("WxReadCnt get error message " + errorinfo);
                            //打日志，打出错误代码
                        }
                    } else {
                        result = "{\"code\":-3,\"errorinfo\":\"请求超时\",\"data\":\"\"}";
//                            logger.info("WxReadCnt httpClient connect out of time");
                    }

                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }

            } else {
                result = "{\"code\":-4,\"errorinfo\":\"查询访问量超限\",\"data\":\"\"}";
                logger.info("WxReadCnt httpClient connection size is limited ");
            }
            //向mongo库中插入或更新该条记录,参数为主键，需要更新的列名，需要更新的列值
//            mongoHelper.update("keycol", "updatecol", updateValues);
            //释放连接
//            Thread.sleep(1000);
            InputStream inputStream = new ByteArrayInputStream(result.getBytes("UTF-8"));

            while ((bytesReadIn = inputStream.read(bytesContent, 0, 1024 * 2)) > 0) {
                bos.write(bytesContent, 0, bytesReadIn);
            }
            bos.flush();
            bos.close();
            RuntimeEnv.wxReadCntLimit.decrementAndGet();
        } catch (Exception e) {
            logger.error("Filedownload send out error\n" + e.getMessage(), e);
        }
//        finally {
//            mongoHelper.conn.close();
//        }
    }

    @Override
    public void init() throws Exception {

    }
}
